package authentication.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Security;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class Utils {
	
	private static final String FORMAT ="yyyy-MM-dd HH:mm:ss";
	private static   SimpleDateFormat formatter=new SimpleDateFormat(FORMAT);
	
	public static String timeDateToString(Date data){
		return  formatter.format(data);
	}
	public static String timeDateToString(Date data,String format){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
		return  simpleDateFormat.format(data);
	}
	@SuppressWarnings("finally")
	public static Date timeStringToDate(String data){
		Date date =null;
		try {
			date = formatter.parse(data);
		} catch (ParseException e) {
			e.printStackTrace();
		}finally{
			return date;
		}
	}
	
	 public static String getIpAddr(HttpServletRequest request) {      
         String ip = request.getHeader("x-forwarded-for");      
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
            ip = request.getHeader("Proxy-Client-IP");      
        }      
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
            ip = request.getHeader("WL-Proxy-Client-IP");      
         }      
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
             ip = request.getRemoteAddr();      
        }      
       return ip;      
  }
	   public static boolean useList(String[] arr, String targetValue) {
		    return Arrays.asList(arr).contains(targetValue);
	   }
	 
	 public static String jiami(String args) throws UnsupportedEncodingException {  
	    	//添加新安全算法,如果用JCE就要把它添加进去  
	    	byte[] enk = hex("zeromike");//用户名  
	    	Security.addProvider(new com.sun.crypto.provider.SunJCE());  
	    	String password = args;//密码  
	    	byte[] encoded = encryptMode(enk,password.getBytes());  
	    	String pword = Base64.encode(encoded);   
	    	pword=URLEncoder.encode(pword,"UTF-8");
	    	   
	    	return pword;
	    }
	    @SuppressWarnings("restriction")
		public static String jiemi(String args) throws UnsupportedEncodingException {  
	    	if(args.indexOf("+")<0){
	    	args=URLDecoder.decode(args,"UTF-8");
	    	}
	    	//添加新安全算法,如果用JCE就要把它添加进去  
	    	byte[] enk = hex("zeromike");//用户名  
	    	Security.addProvider(new com.sun.crypto.provider.SunJCE());  
	    	  byte[] reqPassword = Base64.decode(args);  
	          byte[] srcBytes = decryptMode(enk,reqPassword);  
	          return  (new String(srcBytes));
	    }
	    
	    public static byte[] hex(String username){  
	        String key = "test";//关键字  
	        String f = DigestUtils.md5Hex(username+key);  
	        byte[] bkeys = new String(f).getBytes();  
	        byte[] enk = new byte[24];  
	        for (int i=0;i<24;i++){  
	            enk[i] = bkeys[i];  
	        }  
	        return enk;  
	    }  
	    private static final String Algorithm = "DESede";
	    public static byte[] decryptMode(byte[] keybyte,byte[] src){  
	        try {  
	            //生成密钥  
	            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
	            //解密  
	            Cipher c1 = Cipher.getInstance(Algorithm);  
	            c1.init(Cipher.DECRYPT_MODE, deskey);  
	            return c1.doFinal(src);  
	        } catch (java.security.NoSuchAlgorithmException e1) {  
	            // TODO: handle exception  
	            e1.printStackTrace();  
	        }catch(javax.crypto.NoSuchPaddingException e2){  
	            e2.printStackTrace();  
	        }catch(java.lang.Exception e3){  
	            e3.printStackTrace();  
	        }  
	        return null;          
	    } 
	    
	    //keybyte为加密密钥，长度为24字节      
	    //src为被加密的数据缓冲区（源）  
	    public static byte[] encryptMode(byte[] keybyte,byte[] src){  
	         try {  
	            //生成密钥  
	            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
	            //加密  
	            Cipher c1 = Cipher.getInstance(Algorithm);  
	            c1.init(Cipher.ENCRYPT_MODE, deskey);  
	            return c1.doFinal(src);//在单一方面的加密或解密  
	        } catch (java.security.NoSuchAlgorithmException e1) {  
	            // TODO: handle exception  
	             e1.printStackTrace();  
	        }catch(javax.crypto.NoSuchPaddingException e2){  
	            e2.printStackTrace();  
	        }catch(java.lang.Exception e3){  
	            e3.printStackTrace();  
	        }  
	        return null;  
	    }  
	    
	    /** 随机数。 */
	    private static int serial = 0;

	    /** 随机数最大值。 */
	    private static final int MAX_SERIAL = 999;

	    /** 随机数长度。 */
	    private static final int SEQUENCE_LENTH = 12;
	    public static synchronized String makeUUID() {
	    	
	        StringBuffer ret = new StringBuffer();
	        SimpleDateFormat dfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	        dfDate.setLenient(false);
	        ret.append(dfDate.format((new GregorianCalendar()).getTime()));     
	        DecimalFormat dfNum = new DecimalFormat("000");
	        ret.append(dfNum.format(serial++));
	        if (serial > MAX_SERIAL) {
	            serial = 0;
	        }
	        UUID uuid = UUID.randomUUID();
	        ret.append(uuid.toString().replace("-", "").subSequence(0, SEQUENCE_LENTH));

	        return ret.toString();
	    }

	    public static synchronized String selfMakeUUID() {
	        String s = UUID.randomUUID().toString();
	        String value = s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
	        return value;
	    }

	    public static boolean isEmptyOrNull(String str) {
	        boolean isEmptyOrNull = true;
	        if (str != null && str.length() != 0) {
	            isEmptyOrNull = false;
	        }
	        return isEmptyOrNull;
	    }
	    

		//发送email
//		public static void sendEmail(Email email){
//			String recipient = email.getRecipient();//收件人邮箱
//	    	String sender = email.getSender();//发件人邮箱
//	    	String subject = email.getSubject();//邮件主题
//	    	String content = email.getContent();//邮件内容
//	    	double size = recipient.length() + sender.length() + subject.length() + content.length();
//	    	String userName = email.getUsername();//发件人账户
//	    	String password = email.getPassword();//发件人密码
//	    	Properties props = new Properties();
//	    	props.put("mail.debug", "true");
//	    	props.put("mail.smtp.host", email.getSmtp());//发件人邮箱服务器地址
//	    	props.put("mail.smtp.port", "25");
//	    	props.put("mail.smtp.auth", "true");
//	    	props.setProperty("mail.transport.protocol", "smtp");
//	    	// 授权用户和密码可以在这设置，也可以在发送时直接设置
//	    	Session session = Session.getDefaultInstance(props, null); 
//	    	Message message = new MimeMessage(session);
//	    	
//	    	try{
//	    	Address sendAddress = new InternetAddress(sender);
//			message.setFrom(sendAddress);
//			// 支持发送多个收件人
//			String [] recipients = recipient.split(";");
//			Address[] recipientAddress = new Address[recipients.length];
//			for (int i = 0; i < recipients.length; i++) {
//				recipientAddress[i] = new InternetAddress(recipients[i]);
//			}
//			message.setRecipients(Message.RecipientType.TO, recipientAddress);
//			message.setSubject(subject);
//			// 以html发送
//			BodyPart bodyPart = new MimeBodyPart();
//			bodyPart.setContent(content, "text/html; charset=utf-8");
//			Multipart multipart = new MimeMultipart();
//			multipart.addBodyPart(bodyPart);
//			// 单纯发送文本的用setText即可
//			// message.setText(content);
//			message.setContent(multipart);
//			Transport  transport= session.getTransport();
//			transport.connect(userName, password);
//			transport.sendMessage(message, recipientAddress);
//	    	}catch (MessagingException e) {
//				// TODO: handle exception
//	    		e.printStackTrace();
//			}
//		}
	    
		
		
		public static String transTime(String time){
			String ti="";
			int h=time.indexOf("时");
			if(h>0){
				ti=time.substring(0,h);
				h+=1;
			}else{
				ti="00";
				h=0;
			}
			ti+=":";
			int m=time.indexOf("分");
			if(m>0){
				ti+=time.substring(h,m);
				m+=1;
			}else{
				ti+="00";
				m=0;
			}
			ti+=":";
			int s=time.indexOf("秒");
			if(s>0){
				ti+=time.substring(m,s);
			}else{
				ti+="00";
			}
			return ti;
		}
	    public static void main(String[] args) {
	    	String transTime = transTime("40秒");
	    	System.out.println(transTime);
		}
}
